package com.ybu.oodd.utils.login;

import com.ybu.oodd.service.UserService;
import com.ybu.oodd.utils.redis.RedisUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.http.HttpStatus;

import java.util.List;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //打印url
        log.info("请求的url: {}", request.getRequestURL());

        //3. 获取请求头中的令牌（token）。
        String jwt = request.getHeader("token");

        //4.1 判断令牌是否存在，如果不存在，返回错误结果（未登录）。
        if(!StringUtils.hasLength(jwt)){ //jwt为空
            log.info("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            //5. 解析token，如果解析失败，返回错误结果（未登录）。
            Claims claims = JwtUtils.parseJWT(jwt);

            //校验redis中的token是否一致
            Integer userId = (Integer)claims.get("userId");
            if(!jwt.equals(redisUtil.get(userId+""))){
                log.info("其他设备登录");
                response.setStatus(499);
                return false;
            }



            //将用户信息存入上下文
            ContextHolder.init();
            ContextHolder.put("userId", userId);

            //活跃用户标记
            String key = "active-" + userId.toString();
            redisUtil.set(key,"a",300L);
        } catch (Exception e) {
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        //6. 放行。
        log.info("令牌合法, 放行");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除上下文
        ContextHolder.clear();
    }
}